package org.jiamandan.com.strategy;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;
import org.jiamandan.com.cache.CacheNames;
import org.jiamandan.com.config.TcpInboundAdapter;
import org.jiamandan.com.strategy.enums.ZDEventTagEnum;
import org.jiamandan.com.strategy.impl.tram.TramBasicService;
import org.jiamandan.com.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class ZDIssueContextService {

    @Resource
    private final Map<String, TramBasicService> issueMap = new ConcurrentHashMap<>();
    @Resource
    private RedisUtil redisUtil;

    public ZDIssueContextService(Map<String, TramBasicService> strategyMap) {
        this.issueMap.clear();
        strategyMap.forEach((k, v) -> this.issueMap.put(k, v));
    }

    public Boolean issureExecute(byte[] data, String deviceNo, String cmd) throws Exception {
        Map<String, ChannelId> channels = (Map<String, ChannelId> ) redisUtil.get(CacheNames.TCP_CHANNEL);
        log.info("channels:" + channels.toString());
        if (channels == null || channels.get(deviceNo) == null) {
            log.error(deviceNo+":未找到相关发送通道ID");
            return false;
        }
        Channel channel = TcpInboundAdapter.clients.find(channels.get(deviceNo));
        if (channel == null) {
            log.error(deviceNo+":未找到相关发送通道");
            return false;
        }
        log.info("channelid："+channels.get(deviceNo));
        log.info("cmd：" + cmd);
        String classKey = ZDEventTagEnum.getValueByKey(cmd);
        TramBasicService service = this.issueMap.get(classKey);
        if (service != null) {
            log.info("开始调用相关监听类：" + service.getClass());
            service.doExecute(data, channel);
            return true;
        } else {
            log.error("找不到相关类：" + classKey + "| 命令CMD：" + cmd);
            return false;
        }
    }
}
